import axios, { AxiosRequestConfig } from 'axios'
import { ParamsType } from './axios.dto'
import { useTokenStore } from '@/stores/token/token.store'
import { ElMessage } from 'element-plus'

const tokenStore = useTokenStore()

export class HttpService {
  static get<T>(url: string, params?: ParamsType, options?: AxiosRequestConfig): Promise<T> {
    const axiosOptions: AxiosRequestConfig = {
      method: 'get',
      url,
      params,
      ...options
    }
    return this.request<T>(axiosOptions)
  }

  static post<T>(url: string, data?: ParamsType, options?: AxiosRequestConfig): Promise<T> {
    const axiosOptions: AxiosRequestConfig = {
      method: 'post',
      url,
      data,
      ...options
    }
    return this.request<T>(axiosOptions)
  }

  static async request<T>(options: AxiosRequestConfig): Promise<T> {
    options.withCredentials = true
    options.params = Object.assign(
      {
        token: tokenStore.token
      },
      options.params
    )
    options.baseURL = import.meta.env.VITE_API_BASE_URL
    const response = await axios(options).catch((error: any) => {
      ElMessage({
        message: error.message || '请求失败',
        type: 'error'
      })
      return error
    })
    return response?.data
  }
}
